import { message } from 'antd';
import { push } from 'react-router-redux';
import API from '../api/auth/index';
import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILED, REFRESH_CAPTCHA } from '../constants/ActionTypes';

const uuidv4 = require('uuid/v4');

const setLoginStatus = (type, loginStatus) => ({ type, loginStatus });
const refreshCaptcha = (type, captcha) => ({ type, captcha });

const getCpatcha = params => async (dispatch) => {
  try {
    const response = await API.getCaptcha(params);
    const imgSrc = URL.createObjectURL(response);
    dispatch(refreshCaptcha(REFRESH_CAPTCHA, imgSrc));
    dispatch(setLoginStatus(LOGIN_SUCCESS, 0));
  } catch (error) {
    dispatch(setLoginStatus(LOGIN_SUCCESS, 0));
    message.error('验证码获取失败，请重试!');
  }
};

const generateUUID = () => {
  const uuid = window.sessionStorage.getItem('captchaUUID') || uuidv4();
  window.sessionStorage.setItem('captchaUUID', uuid);
  return uuid;
};

const login = params => async (dispatch) => {
  try {
    dispatch(setLoginStatus(LOGIN_REQUEST, 1));
    const response = await API.login(params);
    const { code } = response;
    if (code === 1) {
      const { data } = response;
      const { accessToken, refreshToken } = data;
      window.localStorage.setItem('accessToken', accessToken);
      window.localStorage.setItem('refreshToken', refreshToken);
      message.success('登录成功!');
      dispatch(setLoginStatus(LOGIN_SUCCESS, 2));
      dispatch(refreshCaptcha(REFRESH_CAPTCHA, ''));
      dispatch(push('/dashboard'));
    } else if (code === 20130) {
      dispatch(setLoginStatus(LOGIN_FAILED, 3));
      dispatch(refreshCaptcha(REFRESH_CAPTCHA, ''));
    } else if (code === 20205) { // 验证码错误
      const uuid = generateUUID();
      dispatch(getCpatcha(uuid));
    } else if (code === 20206) {
      const uuid = generateUUID();
      dispatch(getCpatcha(uuid));
      dispatch(setLoginStatus(LOGIN_FAILED, 0));
    } else {
      dispatch(setLoginStatus(LOGIN_FAILED, 0));
      dispatch(refreshCaptcha(REFRESH_CAPTCHA, ''));
    }
  } catch (error) {
    dispatch(setLoginStatus(LOGIN_FAILED, 3));
    message.error('登录失败，请重试!');
  }
};


export default {
  login,
  getCpatcha,
};
